import { inject, ref, watch, watchEffect } from 'vue';
import { FormContextOptions } from '../Form';
import { FormItemContextProps } from '../FormItem';

export default function createField (props: any, emit, defaultValue?: any) {
    let value = ref(props.modelValue ?? defaultValue);

    const ctx: FormContextOptions = inject('CMFormContext', null);
    const data = ctx?.form ?? {};
    const formItem: FormItemContextProps = inject('CMFormItemContext', null);
    const name = formItem?.name || props.name;
    const formInitValue = data && name ? data[name] : undefined;

    if (formInitValue != undefined) {
        value.value = formInitValue;
    }

    watch(() => props.modelValue, (val) =>{
        value.value = val;
    });
    watchEffect(() => {
        const val = value.value;
        emit('update:modelValue', val);
        if (!props.notCreateFiled) {
            ctx?.onChange(name, val);
        }
    })

    return value;
}